package cn.appsys.controller.developer;

import cn.appsys.pojo.*;
import cn.appsys.service.backend.AppService;
import cn.appsys.service.backend.BackendUserService;
import cn.appsys.service.developer.*;
import cn.appsys.tools.Constants;
import cn.appsys.tools.PageSupport;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping(value="/back")
public class BackendUserController {
    private Logger logger = Logger.getLogger(AppInfoController.class);
    @Resource
    private AppInfoService appInfoService;
    @Resource
    private DataDictionaryService dataDictionaryService;
    @Resource
    private AppCategoryService appCategoryService;
    @Resource
    private AppVersionService appVersionService;
    @Resource
    private AppService appService;
    @Resource
    private BackendUserService backendUserService;
    @Resource
    private DevUserService devUserService;

    @RequestMapping(value = "/userList")
    public String getuserList(Model model, HttpSession session,
                                       @RequestParam(value = "queryUserName", required = false) String queryUserName,
                                       @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        System.out.println(pageIndex);

        List<DevUser> userList = null;
        // 页面容量
        int pageSize = Constants.pageSize;
        // 当前页码
        Integer currentPageNo = 1;
        // 判断当前页面是否为空
        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        // 获取总数量
        int totalCount = 0;
        try {
            totalCount = devUserService.getUserCount(queryUserName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用page工具类获取总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        // 控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        System.out.println(currentPageNo+"  "+pageSize);
        try {
            userList = devUserService.getUserList(queryUserName,currentPageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取session用户的id
        Integer backId = ((BackendUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId();
        model.addAttribute("backId",backId);
        model.addAttribute("userList", userList);
        model.addAttribute("pages", pages);
        model.addAttribute("queryUserName",queryUserName);

        return "backend/userList";
    }
    @RequestMapping(value = "/userCheckList")
    public String getUserCheckInfoList(Model model, HttpSession session,
                                 @RequestParam(value = "queryUserName", required = false) String queryUserName,
                                 @RequestParam(value = "pageIndex", required = false) String pageIndex) {

        List<DevUser> userCheckInfoList = null;
        // 页面容量
        int pageSize = Constants.pageSize;
        // 当前页码
        Integer currentPageNo = 1;
        // 判断当前页面是否为空
        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        // 获取总数量
        int totalCount = 0;
        try {
            totalCount = backendUserService.getUserCheckInfoCount(queryUserName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用page工具类获取总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        // 控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        try {
            userCheckInfoList = backendUserService.getUserCheckInfoList(queryUserName,currentPageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取session用户的id
        Integer backId = ((BackendUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId();
        model.addAttribute("backId",backId);
        model.addAttribute("userCheckInfoList", userCheckInfoList);
        model.addAttribute("pages", pages);
        model.addAttribute("queryUserName",queryUserName);

        return "backend/userCheckList";
    }


    @RequestMapping(value = "/list")
    public String getAppInfoList(Model model, HttpSession session,
                                 @RequestParam(value = "querySoftwareName", required = false) String querySoftwareName,
                                 @RequestParam(value = "queryStatus", required = false) String _queryStatus,
                                 @RequestParam(value = "queryCategoryLevel1", required = false) String _queryCategoryLevel1,
                                 @RequestParam(value = "queryCategoryLevel2", required = false) String _queryCategoryLevel2,
                                 @RequestParam(value = "queryCategoryLevel3", required = false) String _queryCategoryLevel3,
                                 @RequestParam(value = "queryFlatformId", required = false) String _queryFlatformId,
                                 @RequestParam(value = "pageIndex", required = false) String pageIndex) {

        // 获取session用户的id
        Integer devId = ((BackendUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId();
        List<AppInfo> appInfoList = null;
        List<DataDictionary> statusList = null;
        List<DataDictionary> flatFormList = null;
        List<AppCategory> categoryLevel1List = null;// 列出一级分类列表，注：二级和三级分类列表通过异步ajax获取
        List<AppCategory> categoryLevel2List = null;
        List<AppCategory> categoryLevel3List = null;
        // 页面容量
        int pageSize = Constants.pageSize;
        // 当前页码
        Integer currentPageNo = 1;
        // 判断当前页面是否为空
        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        /**
         * 判断信息是否为空防止类型错误 防止用户使用时出现字符乱码的异常
         */
        Integer queryStatus = null;
        if (_queryStatus != null && !_queryStatus.equals("")) {
            queryStatus = Integer.parseInt(_queryStatus);
        }
        Integer queryCategoryLevel1 = null;
        if (_queryCategoryLevel1 != null && !_queryCategoryLevel1.equals("")) {
            queryCategoryLevel1 = Integer.parseInt(_queryCategoryLevel1);
        }
        Integer queryCategoryLevel2 = null;
        if (_queryCategoryLevel2 != null && !_queryCategoryLevel2.equals("")) {
            queryCategoryLevel2 = Integer.parseInt(_queryCategoryLevel2);
        }
        Integer queryCategoryLevel3 = null;
        if (_queryCategoryLevel3 != null && !_queryCategoryLevel3.equals("")) {
            queryCategoryLevel3 = Integer.parseInt(_queryCategoryLevel3);
        }
        Integer queryFlatformId = null;
        if (_queryFlatformId != null && !_queryFlatformId.equals("")) {
            queryFlatformId = Integer.parseInt(_queryFlatformId);
        }

        // 获取总数量
        int totalCount = 0;
        try {
            totalCount = appInfoService.getAppInfoCount(querySoftwareName, queryStatus, queryCategoryLevel1,
                    queryCategoryLevel2, queryCategoryLevel3, queryFlatformId, devId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用page工具类获取总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        // 控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        try {
            appInfoList = appInfoService.getAppInfoList(querySoftwareName, queryStatus, queryCategoryLevel1,
                    queryCategoryLevel2, queryCategoryLevel3, queryFlatformId, devId, currentPageNo, pageSize);
            // 进行判断三级分类类型
            statusList = this.getDataDictionaryList("APP_STATUS");
            flatFormList = this.getDataDictionaryList("APP_FLATFORM");
            categoryLevel1List = appCategoryService.getAppCategoryListByParentId(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("appInfoList", appInfoList);
        model.addAttribute("statusList", statusList);
        model.addAttribute("flatFormList", flatFormList);
        model.addAttribute("categoryLevel1List", categoryLevel1List);
        model.addAttribute("pages", pages);
        model.addAttribute("queryStatus", queryStatus);
        model.addAttribute("querySoftwareName", querySoftwareName);
        model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
        model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
        model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
        model.addAttribute("queryFlatformId", queryFlatformId);

        // 二级分类列表和三级分类列表---回显
        if (queryCategoryLevel2 != null && !queryCategoryLevel2.equals("")) {
            categoryLevel2List = getCategoryList(queryCategoryLevel1.toString());
            model.addAttribute("categoryLevel2List", categoryLevel2List);
        }
        if (queryCategoryLevel3 != null && !queryCategoryLevel3.equals("")) {
            categoryLevel3List = getCategoryList(queryCategoryLevel2.toString());
            model.addAttribute("categoryLevel3List", categoryLevel3List);
        }
        return "backend/applist";
    }

    public List<DataDictionary> getDataDictionaryList(String typeCode) {
        List<DataDictionary> dataDictionaryList = null;
        try {
            dataDictionaryList = dataDictionaryService.getDataDictionaryList(typeCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataDictionaryList;
    }

    public List<AppCategory> getCategoryList(String pid) {
        List<AppCategory> categoryLevelList = null;
        try {
            categoryLevelList = appCategoryService
                    .getAppCategoryListByParentId(pid == null ? null : Integer.parseInt(pid));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return categoryLevelList;
    }

    /**
     * 根据parentId查询出相应的分类级别列表
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/categorylevellist.json", method = RequestMethod.GET)
    @ResponseBody
    public List<AppCategory> getAppCategoryList(@RequestParam String pid) {
        logger.debug("getAppCategoryList pid ============ " + pid);
        if (pid.equals(""))
            pid = null;
        return getCategoryList(pid);
    }


    @RequestMapping(value = "/check",method = RequestMethod.GET)
    public String check(@RequestParam(value = "aid",required = false) String appId,
                        @RequestParam(value = "vid",required = false) String versionId,
                        Model model){
        AppInfo appInfo = null;
        AppVersion appVersion = null;
        System.out.println(appId+" "+versionId);
        try{
            appInfo = appService.getAppInfo(Integer.parseInt(appId));
            appVersion = appVersionService.getAppVersionById(Integer.parseInt(versionId));
        }catch (Exception e){
            e.printStackTrace();
        }
        model.addAttribute(appVersion);
        model.addAttribute(appInfo);
        return "backend/appcheck";
    }
    @RequestMapping(value = "/checksave",method = RequestMethod.GET)
    public String checkSave(AppInfo appInfo){
        logger.debug("appInfo ============ >"+appInfo.getStatus());
        try{
            if(appService.updateSatus(appInfo.getStatus(),appInfo.getId())){
                return "redirect:/back/list";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "backend/appcheck";
    }
    @RequestMapping(value = "/checkUser",method = RequestMethod.GET)
    public String checkUser(@RequestParam int backId,
                            @RequestParam String devCode){
        devUserService.checkUser(backId,devCode);
        return "redirect:/back/userCheckList";
    }
    @RequestMapping(value = "/reCheckUser",method = RequestMethod.GET)
    public String reCheckUser(@RequestParam int userId){
        devUserService.reCheckUser(userId);
        return "redirect:/back/userList";
    }
    @RequestMapping(value = "/delUser")
    public String delUser(@RequestParam int userId){
        devUserService.deleteUser(userId);
        return "redirect:/back/userList";
    }
    @RequestMapping(value = "/toAddUser")
    public String toAddUser(){
        return "backend/userAdd";
    }
    @RequestMapping(value = "/addUser")
    public String addUser(DevUser devUser){
         devUserService.addUser(devUser);
        return "redirect:/back/userList";
    }
    @RequestMapping(value = "/checkDevUser")
    @ResponseBody
    public String checkDevUser(@RequestParam String devCode){
        DevUser devUser = devUserService.getUserByDDevCode(devCode);
        if ("".equals(devCode) || devCode.isEmpty()){
            return "null";
        }
        if (ObjectUtils.isEmpty(devUser)){
            return "true";
        }
        return "false";
    }


}
